<template>
  <button class="btn" :disabled="dis" :class="classies" @click="handle">
    <template v-if="isSendCode">
      {{ buttonText }}
    </template>
    <slot v-else></slot>
  </button>
</template>
<script>
import { Logger  } from '../helper';
export default {
  name: "Button",
  props: {
    type: {
      type: String
    },
    outline: {
      type: Boolean
    },
    block: {
      type: Boolean
    },
    round: {
      type: Boolean
    },
    to: {
      type: String
    },
    disabled: {
      type: Boolean,
      default: false
    },
    isSendCode: {
      type: Boolean,
      default: false
    },
    sendPhoneNo: {
      type: String
    }
  },
  computed: {
    classies() {
      const cls = [];
      if (!this.outline) {
        cls.push(`btn-${this.type}`);
      } else {
        cls.push(`btn-${this.type}-outline`);
      }
      if (this.round) {
        cls.push(`btn-round`);
      }
      if (this.block) {
        cls.push(`btn-block`);
      }
      return cls;
    },
    dis() {
      if (this.isSendCode) {
        return this.canIclick;
      } else {
        return this.disabled;
      }
    }
  },
  watch:{
    sendPhoneNo(newVal){
      Logger.info('none',`
        isSendCode: ${this.isSendCode}
        sendPhoneNo: ${newVal}
        dis : ${this.dis}
      `)
      if (!/1[3578]\d{9}$/.test(newVal)){
       this.canIclick = true 
      }else {
         this.canIclick = false 
      }
    }
  },
  methods: {
    handle() {
      if (this.isSendCode) {
        this._sendVailCode();
      } else {
        if (this.to) {
          this.$router.push(this.to);
        } else {
          this.$emit("click");
        }
      }
    },
    _sendVailCode() {
      this.$service
        .sendVailCode({
          phone: this.sendPhoneNo
        })
        .then(data => {
          alert("验证码已发送，请注意查收");
          this.canIclick = true;
          let time = 30;
          const timeId = setInterval(() => {
            if (time > 0) {
              this.buttonText = `剩下${time}s`;
            } else {
              clearInterval(time);
              this.buttonText = "获取验证码";
            }
            time--;
          }, 1000);
        });
    },
    set(v){
      this.canIclick = v
    }
  },
  data() {
    return {
      canIclick: true,
      buttonText: '获取验证码'
    };
  }
};
</script>

